package org.opencare.tmd.plugin;

import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Logger;
import org.opencare.lib.model.cap.Alert;
import org.opencare.lib.model.edxl.EDXLDistribution;
import org.opencare.tmd.TmdPluginServlet;

public class TopicPublisher implements Publisher {

	static Logger log = Logger.getLogger(TopicPublisher.class);
	private Connection connection;
	private Session session;
	private MessageProducer publisher;
	private Topic topic;

	public TopicPublisher(String brokerUrl, String topicTarget)
			throws JMSException {
		ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(
				brokerUrl);
		connection = factory.createConnection();

		session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		
		topic = session.createTopic(topicTarget);
		publisher = session.createProducer(topic);
		publisher.setDeliveryMode(DeliveryMode.NON_PERSISTENT);				
	}

	public void publish(EDXLDistribution payload) throws JMSException {

		log.info("-------------- Publishing to JMS --------------");
		
		StringBuffer buff = new StringBuffer();
		buff.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
		buff.append(payload.toString());
						
		log.debug(buff.toString());

		connection.start();
		
		TextMessage textMsg = session.createTextMessage();
		
		textMsg.setText(buff.toString());
		
		// Message selector
		log.debug(payload.getSenderID());
		textMsg.setStringProperty("SENDERID", payload.getSenderID());
		
		log.debug(payload.getDistributionStatus().name());
		textMsg.setStringProperty("DISTRIBUTIONSTATUS", payload.getDistributionStatus().name());
		
		log.debug(payload.getDistributionType().name());
		textMsg.setStringProperty("DISTRIBUTIONTYPE", payload.getDistributionType().name());
		
		Alert alert = payload.getContentObject().get(0).getXmlContent().getEmbeddedXMLContent().get(0).getAlert().get(0);
		
		log.debug(alert.getInfo().get(0).getCategories()[0].name());
		textMsg.setStringProperty("CATEGORY", alert.getInfo().get(0).getCategories()[0].name());
		
		log.debug(alert.getInfo().get(0).getParameter("alertLevel"));
		textMsg.setStringProperty("ALERTLEVEL", alert.getInfo().get(0).getParameter("alertLevel"));
		
		publisher.send(textMsg);				
		
		connection.stop();
		
		log.info("-------------- Published --------------");
	}
}
